<template>
	<div style="padding:0 30px 50px;">
		<!--搜索输入框-->
		<div class="search">
			<div class="search-input">
				<div>
					<label for="">{{ $t('search.RefNo') }}：</label>
					<el-input v-model="searchOrderData.outTradeNo" class="block-ipt"></el-input>
				</div>
				<div v-if="showSubAccountNo">
					<label for="">{{ $t('search.SubAccountNo') }}：</label>
					<el-input v-model="searchOrderData.subMchId" class="block-ipt"></el-input>
				</div>
				<div>
					<label for="">{{ $t('search.AgentName') }}：</label>
					<el-input v-model="searchOrderData.dName" class="block-ipt" :maxlength=100 ></el-input>
				</div>
				<div>
					<label for="">{{ $t('search.MerchantName') }}：</label>
					<el-input v-model="searchOrderData.name" class="block-ipt" :maxlength=100 ></el-input>
				</div>
				<div>
					<label for="">{{ $t('search.TransactionStatus') }}：</label>
					<el-select :placeholder="$t('placeH.All')" v-model="searchOrderData.setllment" clearable class='filter-item condition block-ipt'>
						<el-option :value="$t('search.SettledDone')"></el-option>
						<el-option :value="$t('search.NotSettled')"></el-option>
					</el-select>
				</div>
				<div>
					<label for="">{{$t('search.TransactionCompleted')}}：</label>
					<el-select :placeholder="$t('placeH.All')" v-model="searchOrderData.tradeState" clearable class='filter-item condition block-ipt'>
						<el-option :value="$t('search.Yes')"></el-option>
						<el-option :value="$t('search.No')"></el-option>
					</el-select>
				</div>
				<div>
					<label for="">{{$t('search.TransactionType')}}：</label>
					<el-select :placeholder="$t('placeH.All')" v-model="searchOrderData.trade" clearable class='filter-item condition block-ipt'>
						<el-option :value="$t('trade.Payment')"></el-option>
						<el-option :value="$t('trade.Refund')"></el-option>
					</el-select>
				</div>
				<div>
					<label for="">{{$t('search.SelectBeginTime')}}：</label>
					<el-date-picker :editable=false class="filter-item block-ipt" type="date" v-model="searchOrderData.startDate"></el-date-picker>
				</div>
				<div>
					<label for="">{{$t('search.SelectEndTime')}}：</label>
					<el-date-picker :editable=false class="filter-item block-ipt" type="date" v-model="searchOrderData.endDate"></el-date-picker>
				</div>
			</div>
			<div class="search-btn">
				<el-button class="blue-btn mini2-btn" @click="handleFilter">{{$t('button.search')}}</el-button>
				<el-button class="blue-btn mini2-btn" @click='delSelect()'>{{$t('button.Reset')}}</el-button>
				<el-button class="blue-btn max-btn btn-clearance" @click="getOrderList(orderFormData)">{{$t('button.RefreshStatus')}}</el-button>
				<el-button class="blue-btn max-btn btn-clearance" @click='export2Excel()'>{{$t('button.SaveResult')}}</el-button>
			</div>
		</div>
		<!--交易流水表单-->
		<template>
			<div class="table-border">
				<div class="table-head">{{$t('trade.MerchantRef1')}}</div>
				<el-table :data="tradeDatas" style="width: 100%;" height=400>
					<el-table-column type="index" fixed :label="$t('index.Number')" width="70"></el-table-column>
					<el-table-column prop="outTradeNo" :label="$t('search.RefNo1')" width="250"></el-table-column>
					<el-table-column prop="tradeNo" :label="$t('trade.TransactionNo')" width="265"></el-table-column>
					<el-table-column v-if='false' prop="no" :label="$t('trade.MerchantRefNo')" width="250"></el-table-column>
					<el-table-column prop="merchantName" :label="$t('search.MerchantName1')" width="155"> </el-table-column>
					<el-table-column v-if="showSubAccountNo" prop="merid" :label="$t('search.SubAccountNo1')" width="165"></el-table-column>
					<el-table-column prop="dbname" :label="$t('search.AgentName2')" width="130"></el-table-column>
					<el-table-column prop="addedDate" :label="$t('trade.Time')" width="200"></el-table-column>
					<el-table-column prop="money" :label="$t('trade.Amount') + currency" width="150" :formatter='judgeMoney'></el-table-column>
					<el-table-column prop="payType" :label="$t('trade.TransactionType')" width="170" :formatter='judgePayType'></el-table-column>
					<el-table-column prop="payType" :label="$t('trade.PaymentMethod')" width="165" :formatter='judgePayMethod'></el-table-column>
					<el-table-column prop="tradeState" :label="$t('search.TransactionCompleted1')" width="215" :formatter='judgePayResult'></el-table-column>
					<el-table-column prop="setllment" :label="$t('search.TransactionStatus1')" width="130" :formatter='judgeSetllment'></el-table-column>
					<el-table-column prop="deviceType" :label="$t('trade.Device')" width="120" :formatter='judgeDevice'></el-table-column>
					<el-table-column prop="deviceNo" :label="$t('trade.DeviceID')" width="120"></el-table-column>
					<el-table-column prop="cashierName" :label="$t('trade.Staff')" width="120">
					</el-table-column>
				</el-table>
				<div class="pagination-container">
					<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="searchOrderData.page" :page-sizes="[10,20,30,50]" :page-size="searchOrderData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
				</div>
			</div>
		</template>
	</div>
</template>
<script>
	import { orderAll, orderCorrect, orderPage, merchantOrderAll } from 'api/orderQuery/index';
	import XLSX from 'xlsx'
	import XLSX_SAVE from 'file-saver'

	function s2ab(s) {
		const buf = new ArrayBuffer(s.length);
		const view = new Uint8Array(buf);
		for(let i = 0; i !== s.length; ++i) {
			view[i] = s.charCodeAt(i) & 0xFF;
		}
		return buf;
	}
	export default {
		name: 'tradingFlow',
		data() {
			return {
				currency:localStorage.getItem('companyId') === '2' ? '(A$)' : '(HK$)',
				tradeDatas: [],
				value: '',
				input: '',
				dialogImageUrl: '',
				dialogVisible: false,
				input: '',
				res: [],
				searchOrderData: {
					outTradeNo: '',
					name: '',
					dName: '',
					startDate: '',
					endDate: '',
					page: 1,
					pageSize: 10,
					subMchId: '',
					tradeState: '',
					trade: '',
					setllment: ''
				},
				//第一次进订单查询默认展示的数据所需的参数
				orderFormData: {},
				userType:localStorage.getItem('userType'),
				showSubAccountNo:true,
			}
		},
		created() {
			this.getOrderList(this.orderFormData);
			this.showSubAccountNo = this.userType === '1' ? false : true;
		},
		methods: {
			//交易结果
			judgePayResult(row){
				let payResult = row.tradeState;
				return payResult = payResult === "SUCCESS" ? this.$t('search.Yes') : this.$t('search.No');
			},
			//设备
			judgeDevice(row) {
				let device = row.deviceType;
				if(device === '0') {
					return device = this.$t('inputBox.QRcode');
				}
				if(device === '1') {
					return device = this.$t('trade.Box');
				}
				if(device === '2') {
					return device = this.$t('trade.AppPay');
				}
				if(device === '3') {
					return device = this.$t('trade.SubordinateMerchant');
				}
			},
			//结算状态
			judgeSetllment(row) {
				let formatSetllment = row.setllment;
				if(formatSetllment === 0) {
					return formatSetllment = this.$t('search.NotSettled');
				}
				if(formatSetllment !== 0) {
					return formatSetllment = this.$t('search.SettledDone');
				}
			},
			//支付方式
			judgePayMethod(row) {
				let showType = row.payType;
				if(showType === "WECHAT_MICRO_PAY" || showType === "11") {
					return showType = this.$t('search.WeChatPaySweep');
				}
				if(showType === "WECHAT_SCAN_PAY" || showType === "12") {
					return showType = this.$t('search.WeChatPayScan');
				}
				if(showType === "WECHAT_JS_PAY" || showType === "13") {
					return showType = this.$t('search.OAPayment');
				}
			},
			//格式化提现金额
			judgeMoney(row) {
				let formatMoney = row.money
				return formatMoney = this.fmoney(formatMoney,2);
			},
			 // 格式化金额
			fmoney(s, n){   
				s = s / 100;
				n = n > 0 && n <= 20 ? n : 2;   
				s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
				var l = s.split(".")[0].split("").reverse(),   
				r = s.split(".")[1];   
				let t = "";   
				for(let i = 0; i < l.length; i ++ )   
				{   
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
				}   
				return t.split("").reverse().join("") + "." + r;
			},
			//格式化交易类型
			judgePayType(row) {
				let formatPayType = row.payType
				return formatPayType =  formatPayType === '32' ? this.$t('trade.Refund') : this.$t('trade.Payment') ; 
//				let showType = row.payType;
//				if(showType === "WECHAT_MICRO_PAY" || showType === "11") {
//					return showType = this.$t('search.WeChatPaySweep');
//				}
//				if(showType === "WECHAT_SCAN_PAY" || showType === "12") {
//					return showType = this.$t('search.WeChatPayScan');
//				}
//				if(showType === "WECHAT_JS_PAY" || showType === "13") {
//					return showType = this.$t('search.OAPayment');
//				}
//				if(showType === "WECHAT_JS_PAY" || showType === "32") {
//					return showType = this.$t('trade.Refund');
//				}
			},
			open(state) {
				const h = this.$createElement;
				this.$msgbox({
					title: this.$t("hint.Alert"),
					message: this.$t('hint.SureToSuspendThisMerchant'),
					showClose: false,
					showCancelButton: true,
					confirmButtonText: this.$t('button.OK'),
					cancelButtonText: this.$t('button.Cancel'),
					beforeClose: (action, instance, done) => {
						done();
					}
				})
			},
			getOrderList(value) {
				value.companyId = localStorage.getItem('companyId');
//				value.distributorId = localStorage.getItem('distributorId');
				orderAll(value).then(res => {
					console.log("订单查询返回的数据");
					console.log(res);
					this.res = res.value;
					this.tradeDatas = res.value.list;
//					if(res.value.total === 0) {
//						this.$message({
//							showClose: true,
//							message: this.$t('hint.NoData'),
//							//							type:'error'
//						});
//					}
				}).catch(error => {
					console.log(error);
				})
			},
			delSelect() {
				this.searchOrderData.outTradeNo = '';
				this.searchOrderData.name = '';
				this.searchOrderData.startDate = '';
				this.searchOrderData.endDate = '';
				this.searchOrderData.subMchId = '';
				this.searchOrderData.distributorId = '';
				this.searchOrderData.trade = '';
				this.searchOrderData.tradeState = '';
				this.searchOrderData.setllment = '';
				this.searchOrderData.dName = '';
				this.handleFilter();
			},
			//点击搜索 查询订单
			handleFilter() {
				//查询商户的参数
				const searchOrderData = {};
				$.extend(searchOrderData, this.searchOrderData);
				this.formatObj(searchOrderData);
				//				console.log(searchOrderData);
				//				if(searchOrderData.outTradeNo === ''){
				//					searchOrderData.outTradeNo = null;
				//				}
				//				if(searchOrderData.name === ''){
				//					searchOrderData.name = null;
				//				}
				//				if(searchOrderData.startDate === ''){
				//					searchOrderData.startDate = null;
				//				}
				//				if(searchOrderData.endDate === ''){
				//					searchOrderData.endDate = null;
				//				}
				//				if(searchOrderData.subMchId === ''){
				//					searchOrderData.subMchId = null;
				//				}
				//				if(searchOrderData.distributorId === ''){
				//					searchOrderData.distributorId = null;
				//				}
				//				if(searchOrderData.dName === ''){
				//					searchOrderData.dName = null;
				//				}
				//				if(searchOrderData.trade === ''){
				//					searchOrderData.trade = null;
				//				}
				//				if(searchOrderData.tradeState === ''){
				//					searchOrderData.tradeState = null;
				//				}
				//				if(searchOrderData.setllment === ''){
				//					searchOrderData.setllment = null;
				//				}
				if(searchOrderData.trade === this.$t('trade.Payment')) {
					searchOrderData.trade = 1
				}
				if(searchOrderData.trade === this.$t('trade.Refund')) {
					searchOrderData.trade = 2
				}
				if(searchOrderData.setllment === this.$t('search.SettledDone')) {
					searchOrderData.setllment = 1
				}
				if(searchOrderData.setllment === this.$t('search.NotSettled')) {
					searchOrderData.setllment = 2
				}
				if(searchOrderData.tradeState === this.$t('search.Yes')) {
					searchOrderData.tradeState = 1
				}
				if(searchOrderData.tradeState === this.$t('search.No')) {
					searchOrderData.tradeState = 2
				}
				console.log('设备查询向后台发送的数据');
				console.log(searchOrderData);
				this.getOrderList(searchOrderData);
			},
			//pageSize 改变时会触发
			handleSizeChange(val) {
				this.searchOrderData.pageSize = val;
				//		      console.log(this.listQuery);
				this.handleFilter();
			},
			//currentPage 改变时会触发
			handleCurrentChange(val) {
				this.searchOrderData.page = val;
				this.handleFilter();
			},
			//导出表格
			export2Excel() {
				let length = this.res.total;
				let name = this.searchOrderData.name;
				let startDate = this.searchOrderData.startDate;
				let endDate = this.searchOrderData.endDate;
				let dName = this.searchOrderData.dName;
				let outTradeNo = this.searchOrderData.outTradeNo;
				let setllment = this.searchOrderData.setllment;
				let subMchId = this.searchOrderData.subMchId;
				let trade = this.searchOrderData.trade;
				let tradeState = this.searchOrderData.tradeState;
				require.ensure([], () => {
					let listQuery = {
						page: 1,
						pageSize: length,
						name: name,
						startDate: startDate,
						endDate: endDate,
						companyId: localStorage.getItem('companyId'),
						dName: dName,
						outTradeNo: outTradeNo,
						setllment: setllment,
						subMchId: subMchId,
						trade: trade,
						tradeState: tradeState,
					};
					this.formatObj(listQuery);
					//				console.log(listQuery);
					if(listQuery.trade === this.$t('trade.Payment')) {
						listQuery.trade = 1
					}
					if(listQuery.trade === this.$t('trade.Refund')) {
						listQuery.trade = 2
					}
					if(listQuery.setllment === this.$t('search.SettledDone')) {
						listQuery.setllment = 1
					}
					if(listQuery.setllment === this.$t('search.NotSettled')) {
						listQuery.setllment = 2
					}
					if(listQuery.tradeState === this.$t('search.Yes')) {
						listQuery.tradeState = 1
					}
					if(listQuery.tradeState === this.$t('search.No')) {
						listQuery.tradeState = 2
					}
					orderAll(listQuery).then(res => {
						const { export_json_to_excel } = require('../../vendor/Export2Excel');
						const tHeader = [this.$t('search.RefNo'), this.$t('trade.TransactionNo'), this.$t('search.MerchantName'), this.$t('search.SubAccountNo'), this.$t('search.AgentName'), this.$t('trade.Time'), this.$t('trade.Amount') + this.currency , this.$t('search.TransactionType'), this.$t('trade.PaymentMethod'), this.$t('search.TransactionCompleted'), this.$t('search.TransactionStatus'), this.$t('trade.Device'), this.$t('trade.DeviceID'),this.$t('trade.Staff')]; //对应表格输出的title
						const filterVal = ['outTradeNo', 'tradeNo', 'merchantName', 'merid','dbname', 'addedDate', 'money','payMethod','payType','tradeState','setllment','deviceType','deviceNo','cashierName']; // 对应表格输出的数据
						const list = res.value.list;
						for(let i = 0; i < list.length; i++) {
							list[i].money = list[i].money / 100;
							if(list[i].payType === '11'){
								list[i].payType = this.$t('search.WeChatPaySweep');
								list[i].payMethod = this.$t('trade.Payment');
							}
							if(list[i].payType === '12'){
								list[i].payType = this.$t('search.WeChatPayScan');
								list[i].payMethod = this.$t('trade.Payment');
							}
							if(list[i].payType === '13'){
								list[i].payType = this.$t('search.OAPayment');
								list[i].payMethod = this.$t('trade.Payment');
							}
							if(list[i].payType === '32'){
								list[i].payType = '';
								list[i].payMethod = this.$t('trade.Refund');
							}
							if(list[i].setllment === 0){
								list[i].setllment = this.$t('search.NotSettled');
							} else if(list[i].setllment !== 0){
								list[i].setllment = this.$t('search.SettledDone');
							}
							if(list[i].deviceType === '0') {
								list[i].deviceType = this.$t('inputBox.QRcode');
							}
							if(list[i].deviceType === '1') {
								list[i].deviceType = this.$t('trade.Box');
							}
							if(list[i].deviceType === '2') {
								list[i].deviceType = this.$t('trade.AppPay');
							}
							if(list[i].deviceType === '3') {
								list[i].deviceType = this.$t('trade.SubordinateMerchant');
							}
							if(list[i].tradeState === "SUCCESS" ){
 								list[i].tradeState = this.$t('search.Yes');
							} else{
								list[i].tradeState = this.$t('search.No');
							}
						}
						const data = this.formatJson(filterVal, list);        
						export_json_to_excel(tHeader, data, this.$t('index.MerchantOrders')); //对应下载文件的名字
					})
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			formatObj(obj) {
				let arr = Object.keys(obj);
				for(let i = 0; i < arr.length; i++) {
					if(obj[arr[i]] === '') {
						obj[arr[i]] = null;
					}
				}
			},
		}
	}
</script>

<style scoped>

</style>